<!--
 * @Description: 供应链购物车
 * @Author: Kerwin
 * @Date: 2025-09-13 13:44:05
 * @LastEditTime: 2025-10-16 11:16:21
 * @LastEditors:  Please set LastEditors
-->
<template>
  <scroll-view class="carPage" scroll-y="true" @scrolltolower="onScrollToLower">
    <!-- <view class="carPage"> -->
    <!-- navbar -->
    <view class="scrollBox">
      <view>
        <view class="diagram">
          <view class="navbar">
            <view class="left">
              <image
                style="width: 40rpx; height: 40rpx"
                :src="carIcon"
                mode="scaleToFill"
              />
              <text style="margin: 0 10rpx">{{ backText }}</text>
            </view>
            <view class="right" @click="handleSetting">{{ headerText }}</view>
          </view>
        </view>
        <!-- 内容    padding-bottom: 150rpx; -->
        <view
          class="contentBox"
          :style="{ paddingBottom: props.tabberStatus ? '300rpx' : '150rpx' }"
        >
          <view class="goodItem card" v-for="item in goodsList" :key="item.id">
            <view>
              <!-- <view class="goodName"
            ><u-icon name="bag-fill" color="#fd6135"></u-icon>
            {{ item.shopProductSku.name }}</view
          > -->
              <view class="goodsContent">
                <view class="flex">
                  <u-checkbox
                    v-model="item.checked"
                    shape="circle"
                    @change="checkboxChange"
                  >
                  </u-checkbox>
                  <u-image
                    style="border-radius: 20rpx !important; overflow: hidden"
                    width="180rpx"
                    height="180rpx"
                    mode="heightFix"
                    :src="item.shopProductSku.productSku.image"
                  ></u-image>
                  <view class="goodsInfo">
                    <view class="goodsName">
                      {{ item.shopProductSku.name }}</view
                    >
                    <view class="goodsSpece">
                      规格:
                      <u-tag
                        style="
                          width: 200rpx;
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                          margin-right: 20rpx;
                          font-size: 26rpx;
                          background-color: #fff;
                          border: none;
                          color: #999999;
                        "
                        :text="item.businessAttr || '默认规格'"
                        mode="light"
                      />

                      <van-stepper
                        v-model="item.count"
                        @change="updateCount(item)"
                      />
                    </view>
                    <!-- <view class="goodsFreight">包邮</view> -->
                    <view class="goodsPrice">
                      <view
                        class="price"
                        v-if="
                          item.actualDeductible &&
                          item.actualDeductible > 0 &&
                          (allChecked || item.checked)
                        "
                        ><text style="font-size: 26rpx">券后</text
                        ><text
                          >￥
                          {{
                            moneyUtils.subtract(
                              item.shopProductSku.money * item.count,
                              item.actualDeductible
                            )
                          }}</text
                        >
                      </view>
                      <view class="oldPrice"
                        >原价￥{{
                          item.shopProductSku.money * item.count
                        }}</view
                      >
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view
        class="footer"
        :style="{ bottom: props.tabberStatus ? '130rpx' : '10rpx' }"
      >
        <!-- 全选 -->
        <view style="margin-left: 40rpx"
          ><u-checkbox v-model="allChecked" @change="checkedAll" shape="circle"
            >全选</u-checkbox
          ></view
        >

        <!-- 结算 -->
        <view class="footerBtn">
          <view class="total">
            <view class="priceBox">
              <text>合计:</text>
              <text class="icon">￥</text>
              <text class="price1 fw-700">{{ totalSpecialPrice }}</text>
              <!-- <text class="price2 fw-700">.00</text> -->
              <!-- <text class="price3"
              ><image
                style="width: 35rpx; height: 35rpx"
                :src="quan"
                mode="scaleToFill"
              />
              10</text
            > -->
            </view>
            <view class="preference">
              {{ enumAll.SHOPMODEL[mode] }}抵扣:<text
                style="color: #f23424; font-size: 30rpx"
                >￥{{ deductible }}</text
              >
            </view>
            <view class="oldPrice" v-if="totalPayment">
              原价:￥{{ totalPayment }}
            </view>
          </view>

          <van-button
            @click="handleBtnDel"
            style="width: 200rpx"
            v-if="footerStatus"
            color="linear-gradient(to right, #ff6034, #ee0a24)"
            >{{ footerText }}</van-button
          >
          <van-button
            style="width: 200rpx"
            @click="handleBtnGoOrder"
            v-else
            color="#ff6c18"
          >
            {{ footerText }}
          </van-button>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { watch, reactive, ref, computed } from 'vue'
import {
  onReady,
  onShow,
  onLoad,
  onReachBottom,
  onPageScroll,
  onShareAppMessage,
  onPullDownRefresh
} from '@dcloudio/uni-app'
//api
import { productApi, enumAll, baseApi } from '@/api'
//组件
import ProductList from '../../components/goodsList.vue'
//工具
import { moneyUtils } from '@/utils/money'
//存储
import { userGylCarStore } from '@/store'
//图片
import carIcon from '../../static/carIcon.png'
import quan from '../../static/quan2.png'
import { get } from 'lodash'

//初始化数据
const props = defineProps({
  cartList: {
    type: Array,
    default: () => []
  },
  tabberStatus: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['refreshCarList'])
const gylStore = userGylCarStore()
const mode = ref<any>(null) //模式
const backText = ref('鑫复来购物车')
const goodsList = ref<any>([])
const deductibleDisplay = ref(0) // 显示的抵扣金额
const allChecked = ref(false) //全选
const footerStatus = ref(false) //底部购物
const tabbarHeight = ref(computed(() => props.tabberStatus)) //底部高度
const footerText = ref('去结算') //底部购物
const headerText = ref('管理') //顶部编辑
// 分页相关数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
  loading: false,
  noMoreData: false
})
const shopGYL_Id = ref(0) //供应链店铺id

// 供应链商店id
const getGYL_SHOP_Id = (id: any) => {
  switch (Number(id)) {
    case 4:
      shopGYL_Id.value = baseApi.advertising_enum.XFL_GYL_SHOP
      break

    default:
      uni.showToast({ title: '请先清空软件，再进入', icon: 'error' })
      break
  }
}
// #region ************ 商品列表 ********************** */
// 滚动到底部时加载更多
const cartProductListRef = ref()
const onScrollToLower = () => {
  cartProductListRef.value?.loadMore()
}

// 点击取商品详情
const gotoGoodsDetail = (item: any) => {
  uni.navigateTo({
    url: `/packageG/pages/goods/goodsDetail?id=${item.productId}`
  })
}

// 编辑数量
const updateCount = async (item: any) => {
  goodsList.value.forEach((o: any) => {
    o.checked = false
    if (o.id == item.id) {
      item.checked = true
    }
  })
  const { code } = await productApi.productCartUpdate({
    id: item.id,
    count: item.count
  })
  if (code != 200) {
    uni.showToast({
      title: `更改数量失败`,
      icon: 'none'
    })
  }
  calculateDeductibleByOrder()
}

// 删除购物车
const handleSetting = () => {
  footerStatus.value = !footerStatus.value
  if (footerStatus.value) {
    headerText.value = '完成'
    footerText.value = '删除'
  } else {
    headerText.value = '管理'
    footerText.value = '去结算'
  }
}

// #endregion

// #region ************ 复选框 ********************** */
// 选中某个复选框时，由checkbox时触发
const checkboxChange = (e: any) => {
  // 当商品列表变化时重新计算
  // calculateDeductibleByOrder()
}

// 全选
const checkedAll = (e: any) => {
  if (e.value) {
    goodsList.value.forEach((item: any) => {
      item.checked = true
    })
  } else {
    goodsList.value.forEach((item: any) => {
      item.checked = false
    })
  }
  // 当商品列表变化时重新计算
  calculateDeductibleByOrder()
}

// 计算总支付金额和总优惠金额
// 优惠券总抵扣
const totalDiscount = computed(() => {
  const discount = goodsList.value
    .filter((o: any) => o.checked)
    .reduce((sum: any, item: any) => sum + item.availableTicket * item.count, 0)

  return Math.floor(discount) // 处理成整数
})
//能抵扣的金额
const deductible = computed(() => {
  const allDiscount = totalDiscount.value
  const discount = gylStore.discount
  const result = allDiscount > discount ? discount : allDiscount

  gylStore.setDeductible(result)
  return Math.floor(result) // 处理成整数
})
// 原价总支付金额
const totalPayment = computed(() => {
  return goodsList.value
    .filter((o: any) => o.checked)
    .reduce(
      (sum: any, item: any) =>
        moneyUtils.formatPrice(sum + item.shopProductSku.money * item.count),
      0
    )
})

//优惠价的总金额
const totalSpecialPrice = computed(() => {
  return moneyUtils.subtract(totalPayment.value, deductible.value)
})

// 按顺序计算可抵扣金额
const calculateDeductibleByOrder = () => {
  const selectedItems = goodsList.value.filter((item: any) => item.checked)
  let remainingDeductible = deductible.value
  let totalUsed = 0

  // 按商品在列表中的顺序处理
  selectedItems.forEach((item: any) => {
    const itemAvailable = item.availableTicket * item.count || 0
    const actualDeductible = Math.min(itemAvailable, remainingDeductible)

    // 为每个商品设置实际可抵扣金额（可用于UI展示）
    item.actualDeductible = actualDeductible

    totalUsed += actualDeductible
    remainingDeductible -= actualDeductible
  })
  // 设置全选状态
  const allStauts = goodsList.value.every((item: any) => item.checked)
  if (allStauts) {
    allChecked.value = true
  } else {
    allChecked.value = false
  }
  // goodsList.value = selectedItems
  // 更新显示的抵扣金额
  deductibleDisplay.value = totalUsed
}

//#endregion

// #region ************ 底部按钮 ********************** */
// 删除
const handleBtnDel = async () => {
  // 删除
  if (footerStatus.value) {
    const ids = goodsList.value
      .filter((val: any) => val.checked)
      .map((val: any) => val.id)

    const { data, code } = await productApi.productCartDelete({
      ids: ids
    })
    if (code == 200) {
      uni.showToast({
        title: `删除成功`,
        icon: 'success'
      })
      gylStore.clearData()
      emit('refreshCarList')
    } else {
      uni.showToast({
        title: `删除失败`,
        icon: 'error'
      })
    }
  }
}

//结算
const handleBtnGoOrder = () => {
  const chooseList = goodsList.value
    .filter((item: any) => item.checked)
    .map((o: any) => {
      o.businessAttr
      return {
        ...o,
        otherCheckStr: o.businessAttr
      }
    })
  if (chooseList.length <= 10) {
    gylStore.setChooseList(chooseList)
    gylStore.setDeductible(deductible.value)
    uni.navigateTo({
      url: '/packageG/pages/supplyChainOrder/orderDetail?orderStatus=10&orderType=1'
    })
  } else {
    uni.showToast({
      title: '最多只能选择10个商品',
      icon: 'error'
    })
  }
}
// #endregion

// #region ************ 处理购物车list ********************** */
// 获取优惠券信息
const getDiscountTicket = async () => {
  try {
    // 设置店铺模式到 Store
    gylStore.setShopMode(mode.value)

    // 从 Store 获取优惠券信息
    await gylStore.getDiscountTicket(mode.value)
  } catch (error: any) {
    console.error('获取优惠券失败:', error.msg)
    uni.showToast({
      title: '获取优惠券失败',
      icon: 'none'
    })
  }
}

watch(
  () => props.cartList,
  (newVal) => {
    if (newVal) {
      mode.value = uni.getStorageSync('shopMode')
      //模式
      gylStore.setShopMode(mode.value)
      const list = newVal
      goodsList.value = list.map((item: any) => {
        const shopProductSku = item.shopProductSku

        // 设置原价
        gylStore.money = shopProductSku.money
        // 设置最高抵扣
        gylStore.setHighestScoreMoney(shopProductSku.highestScoreMoney)

        // 计算当前可用的优惠券金额（从 Store 获取）
        const availableTicket = computed(() => gylStore.availableTicket)
        // 计算展示价格 (使用 Store 的计算方法)
        const displayPrice = computed(() => gylStore.displayPrice)

        return {
          ...item,
          displayPrice: displayPrice.value,
          availableTicket: availableTicket.value
        }
      })
    }
  },
  {
    immediate: true
  }
)

watch(
  () => [goodsList.value, allChecked.value],
  () => {
    calculateDeductibleByOrder()
  },
  { deep: true }
)

// #endregion
onShow(() => {
  mode.value = uni.getStorageSync('shopMode')
  getGYL_SHOP_Id(mode.value)

  // 确保在组件显示时 store 已经就绪
  if (gylStore && typeof gylStore.setShopMode === 'function') {
    gylStore.setShopMode(mode.value)
  }
})

onLoad((optins: any) => {
  if (optins.mode) {
    mode.value = optins.mode
    uni.setStorageSync('shopMode', optins.mode)
  }
  mode.value = uni.getStorageSync('shopMode')
  if (props.tabberStatus) {
    getDiscountTicket()
  }

  getGYL_SHOP_Id(mode.value)
})
</script>

<style lang="scss" scoped>
.carPage {
  transform: translateX(-20rpx);
  width: calc(100% + 40rpx);
  height: 100%;
  margin-left: 0;
  margin-right: 0;
  .scrollBox {
    padding: 20rpx;
    height: 100vh;
  }

  .diagram {
    margin-top: 10rpx;

    .navbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left {
        display: flex;
        align-items: center;
        margin-left: 40rpx;
      }

      .right {
        margin-right: 40rpx;
        font-size: 30rpx;
        color: #606266;
      }
    }
  }

  .contentBox {
    padding-bottom: 150rpx;
    .noData {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 80rpx 0;
      text-align: center;
    }

    .goodItem {
      margin: 20rpx 0;
      background: #fff;
      .goodName {
        font-size: 30rpx;
        margin-bottom: 30rpx;
      }
      .goodsContent {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .goodsInfo {
          //   width: 220rpx;
          font-size: 26rpx;
          margin-left: 20rpx;
          .goodsName {
            font-size: 26rpx;
            margin-bottom: 20rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 220rpx;
          }
          .goodsSpece {
            display: flex;
            align-items: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #999999;
          }
          .goodsFreight {
            margin: 10rpx 0;
          }
          .goodsPrice {
            display: flex;
            align-items: center;
            margin-top: 20rpx;
            .price {
              font-size: 36rpx;
              font-weight: 700;
              margin-right: 10rpx;
              color: #fd6135;
            }
            .oldPrice {
              font-size: 26rpx;
              color: #fd6135;
              //   color: #999999;
            }
          }

          .discount {
            font-size: 24rpx;
            color: #fd6135;
          }
        }
      }
    }
  }

  .recommendBox {
    .title {
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      margin-bottom: 20rpx;
      .icon-left,
      .icon-right {
        width: 200rpx;
        height: 30rpx;
      }
      .icon-left {
        // margin-left: 20rpx;
        .icon {
          margin-left: 30rpx;
        }
      }
    }
    // .recommend {
    //   // 让商品列表组件直接在页面滚动中加载更多
    //   padding: 0 20rpx;
    // }
  }

  .footer {
    bottom: 0;
    width: 100%;
    height: 140rpx;
    position: fixed;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    z-index: 100;
    padding: 0 40rpx;
    box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);

    .footerBtn {
      display: flex;
      align-items: center;
      margin-right: 20rpx;
      .priceBox {
        color: #f23424;
        margin-right: 20rpx;
        .icon {
          font-size: 20rpx;
        }
        .price1 {
          font-size: 42rpx;
        }
        .price2 {
          font-size: 22rpx;
        }
        .price3 {
          font-size: 28rpx;
        }
      }
      .preference {
        font-size: 26rpx;
      }
      .total {
        font-size: 28rpx;
        margin-right: 20rpx;
        .oldPrice {
          font-size: 26rpx;
          color: #999999;
          text-decoration: line-through;
        }
      }
    }
  }
}

.fw700 {
  font-weight: 700;
}

.card {
  padding: 20rpx;
  margin: 20rpx;

  border-radius: 20rpx;
  backgfloor-color: #fff;
}

:deep(.u-navbar-inner) {
  backgfloor-color: #f6f6f6;
}
</style>
